#!/usr/bin/python
# -*-coding:UTF-8 -*-

# ========================
# @Time  : 2021/2/8
# @Author: Sunny
# ========================

#第一题：基于pymysql模块实现一个数据库操作的上下文管理器（目的：实现自动关闭连接对象和游标）
import pymysql

class MySql:
    def __init__(self,sql,arg=None,all_data=False):
        self.sql = sql
        self.arg = arg
        self.all_data = all_data
        #1.建立连接
        self.conn = pymysql.connect(host='192.168.99.113',
                                    user='bitb_dev',
                                    password='bitb_dev',
                                    db='bessky_test',
                                    port=3306,
                                    charset='utf8',
                                    cursorclass=pymysql.cursors.DictCursor)
        # 2.创建游标
        self.cursor = self.conn.cursor()


    def __enter__(self):
        # #建立连接
        self.cursor.execute(self.sql, self.arg)
        self.conn.commit()
        if self.all_data:
            result = self.cursor.fetchall()
        else:
            result = self.cursor.fetchone()

        return result


    def __call__(self, sql,arg=None,all_data=False):
        """
        执行sql并返回查询的数据
        :param sql: sql语句,字符类型
        :param arg: sql语句的参数，为序列类型
        :param is_more: False or True
        :return: 字典类型或者嵌套字典的列表
        """

    def __exit__(self, exc_type, exc_val, exc_tb):
        #关闭连接
        self.cursor.close()
        self.conn.close()


with MySql("SELECT * FROM t_employee WHERE job_number = '008770'") as db:
    print(db)
